package it.asvp.asvp_portal.data.dao.impl;

import it.asvp.asvp_portal.data.dao.GenericDao;
import it.asvp.asvp_portal.data.entity.domain.BaseEntity;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;

@Repository
public abstract class GenericDaoImpl<K extends Serializable, T extends BaseEntity> implements GenericDao<K, T> {

  @PersistenceContext
  private EntityManager em;

  private Class<T>      entityClass;

  @SuppressWarnings("unchecked")
  public GenericDaoImpl() {
    Type t = getClass().getGenericSuperclass();
    ParameterizedType pt = (ParameterizedType) t;
    Type[] entityTypes = pt.getActualTypeArguments();
    Type entityType = entityTypes[entityTypes.length - 1];
    entityClass = (Class<T>) entityType;
  }

  protected Class<T> getEntityClass() {
    return entityClass;
  }

  protected EntityManager getEntityManager() {
    return em;
  }

  @Override
  public T get(K id) {
    return em.find(entityClass, id);
  }

  @Override
  public T persist(T obj) {
    em.persist(obj);
    return obj;
  }

  @Override
  public T merge(T obj) {
    em.merge(obj);
    return obj;
  }

  @Override
  public void remove(T obj) {
    em.remove(obj);
  }

  @Override
  public void remove(K id) {
    T entity = this.get(id);
    em.remove(entity);
  }
}
